package com.mysql.opt;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


import reflect.engine.DataBaseStructInfoer;
import system.mysql.schema.information.models.TRIGGERS;


public class TriggerOperator extends Operator{
	
	private List<TRIGGERS> triList = null;
	
	public TriggerOperator(){
		this.oprType = "Trigger";
		this.refresh();
	}
	
	@Override
	public boolean drop(int index) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean dropAll() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public List<String[]> getBackupSQLs() {
		// TODO Auto-generated method stub
		List<String[]> SQLs4b = new ArrayList<String[]>();
		for(int i=0;i<this.triList.size();i++){
			TRIGGERS trig = this.triList.get(i);
			String[] back = {"Trigger: "+trig.getTRIGGER_NAME(),this.genCreateStatement(trig)};
			SQLs4b.add(back);
		}
		return SQLs4b;
	}

	@Override
	public List<String> getNames() {
		// TODO Auto-generated method stub
		List<String> nameL = new ArrayList<String>();
		for(int i=0;i<this.triList.size();i++){
			nameL.add(this.triList.get(i).getTRIGGER_NAME());
		}
		return nameL;
	}

	@Override
	public List getObjs() {
		// TODO Auto-generated method stub
		return this.triList;
	}

	@Override
	public void refresh() {
		// TODO Auto-generated method stub
		DataBaseStructInfoer dbTi = new DataBaseStructInfoer();
		this.triList = dbTi.getTriggers();
	}
	
	private String genDropStatement(TRIGGERS tri){
		return "DROP TRIGGER IF EXISTS `"+ tri.getTRIGGER_NAME()+"`;";
	}	
	
	private String genCreateStatement(TRIGGERS tri){
		String stat = "/*TRIGGER : `"+tri.getTRIGGER_SCHEMA() + "`.`" + tri.getEVENT_OBJECT_TABLE()+"` */ " + Operator.nextline;
		stat += this.genDropStatement(tri) + Operator.nextline;
		stat += "CREATE TRIGGER `"+ tri.getTRIGGER_NAME()+"` ";
		stat += tri.getACTION_TIMING() + " " + tri.getEVENT_MANIPULATION() + " ON `" + tri.getEVENT_OBJECT_TABLE() + "` ";
		stat += "FOR EACH " + tri.getACTION_ORIENTATION() + Operator.nextline;
		stat += tri.getACTION_STATEMENT();
		stat += ";";
		return stat;
	}
	
	
	
}
